import json
import os
import re

# 配置基础路径
base_html_path = "/Users/justinzhang/WorkSpace/com.ein/project/南京/angularjs/platform-ui/html/"
base_vue_path = "/Users/justinzhang/WorkSpace/com.ein/demo/angularjs2vue3/RuoYi-Vue/ruoyi-ui/src/views/"

def find_leaf_nodes(nodes, leaves):
    """递归查找所有叶子节点"""
    for node in nodes:
        if 'children' in node and node['children']:
            find_leaf_nodes(node['children'], leaves)
        else:
            leaves.append(node)

def process_leaf(leaf):
    """处理单个叶子节点"""
    try:
        # 获取必要字段
        html_url = leaf['meta']['htmlUrl']
        component = leaf['component']
        js_files = leaf['meta'].get('fileJs', [])

        # 构造完整文件路径
        full_html_path = os.path.join(base_html_path, html_url)
        full_js_paths = [os.path.join(base_html_path, js) for js in js_files]

        # 验证文件存在性
        if not os.path.exists(full_html_path):
            print(f"HTML文件不存在: {full_html_path}")
            return

        # 读取HTML内容并查找控制器
        with open(full_html_path, 'r', encoding='utf-8') as f:
            html_content = f.read()

        controller_match = re.search(r'ng-controller="([^"]+)"', html_content)
        if not controller_match:
            print(f"未找到ng-controller: {full_html_path}")
            return

        controller_name = controller_match.group(1)

        # 在JS文件中查找控制器定义
        controller_code = ""
        for js_path in full_js_paths:
            if not os.path.exists(js_path):
                print(f"JS文件不存在: {js_path}")
                continue

            with open(js_path, 'r', encoding='utf-8') as f:
                js_content = f.read()

            # 使用非贪婪匹配和多行模式
            pattern = re.compile(
                r'\.controller\(\s*["\']' + re.escape(controller_name) +
                r'["\']\s*,\s*function\s*\([^)]*\)\s*{([\s\S]*?)}\s*\)',
                re.DOTALL
            )
            match = pattern.search(js_content)
            if match:
                controller_code = match.group(1).strip()
                break

        if not controller_code:
            print(f"未找到控制器代码: {controller_name}")
            return

        # 构造Vue文件路径
        vue_path = os.path.join(base_vue_path, *component.split('/')) + '.vue'
        os.makedirs(os.path.dirname(vue_path), exist_ok=True)

        # 构造Vue文件内容
        vue_content = f"""<template>
{html_content}
</template>

<script>
export default {{
{convert_angular_to_vue(controller_code)}
}}
</script>
"""

        # 写入Vue文件
        with open(vue_path, 'w', encoding='utf-8') as f:
            f.write(vue_content)
        print(f"成功生成Vue文件: {vue_path}")

    except KeyError as e:
        print(f"字段缺失: {str(e)}")
    except Exception as e:
        print(f"处理节点时出错: {str(e)}")

def convert_angular_to_vue(angular_code):
    """简单转换AngularJS代码到Vue语法"""
    # 替换$scope为this
    converted = re.sub(r'\$scope\.', 'this.', angular_code)
    # 添加data()函数
    converted = re.sub(
        r'(this\.\w+)\s*=\s*([^;]+);',
        r'data() {\n  return {\n    \1: \2\n  };\n},',
        converted
    )
    return converted

if __name__ == "__main__":
    # 加载路由配置
    with open('data.json', 'r', encoding='utf-8') as f:
        routes = json.load(f)

    # 查找所有叶子节点
    leaves = []
    find_leaf_nodes(routes, leaves)

    # 处理每个叶子节点
    for leaf in leaves:
        process_leaf(leaf)
